package com.huanglj.taobaounion.view.customView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.huanglj.taobaounion.utils.LogUtil;

@SuppressLint("AppCompatCustomView")
public class LoadingView extends ImageView {
    private static final String TAG = "LoadingView";

    float rotateDegrees = 0;
    boolean neetRorate = false;
    public LoadingView(Context context) {
        this(context,null);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        setLooper(true);
        super.onAttachedToWindow();
        startLooper();
    }

    public void startLooper() {
        removeCallbacks(task);
        post(task);
    }
    Runnable task = new Runnable() {
        @Override
        public void run() {
            rotateDegrees += 15;
            rotateDegrees = rotateDegrees <= 360 ? rotateDegrees : 0;
            LogUtil.d(TAG,"loading");
            invalidate();
            if(neetRorate && getVisibility()==VISIBLE){
                postDelayed(this,50);
            }else {
                removeCallbacks(this);
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        LogUtil.d(TAG,"onDetachedFromWindow");
        setLooper(false);
        stopLooper();
    }

    public void stopLooper() {
        removeCallbacks(task);
    }

    public void setLooper(boolean b) {
        neetRorate = b;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.rotate(rotateDegrees,getWidth()/2,getHeight()/2);
        super.onDraw(canvas);
    }
}
